package com.ctrip.demo.tree.loop;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.List;

public class LoopTest {

    static class TreeNode {
        TreeNode left;
        TreeNode right;
        int val;

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left,TreeNode right) {
            this.left = left;
            this.val = val;
            this.right = right;
        }
    }

    // 前序遍历
    static class Preorder {
        public static void preorder(TreeNode root, List<Integer> result) {
            if (root == null) {
                return;
            }
            result.add(root.val);
            preorder(root.left, result);
            preorder(root.right, result);
        }
    }
    static class InorderTraversal {

        static void inorder(TreeNode root, List<Integer> res) {
            if (root == null) {
                return;
            }
            inorder(root.left, res);
            res.add(root.val);
            inorder(root.right, res);
        }
    }

    static class PostorderTraversal {

        public static List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            postorder(root, result);
            return result;
        }


        static void postorder(TreeNode root, List<Integer> res) {
            if (root == null) {
                return;
            }
            postorder(root.left, res);
            postorder(root.right, res);
            res.add(root.val);
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(10,new TreeNode(6, new TreeNode(5), new TreeNode(7)), new TreeNode(11, new TreeNode(9), new TreeNode(12)));
        List<Integer> res = new ArrayList<>();

        System.out.println("=====================前序遍历===================");
        Preorder.preorder(treeNode, res);
        res.forEach(System.out::print);
        System.out.println();

        res.clear();
        System.out.println("=====================中序遍历===================");
        InorderTraversal.inorder(treeNode, res);
        res.forEach(System.out::print);
        System.out.println();
        res.clear();
        System.out.println("=====================后序遍历===================");
        PostorderTraversal.postorder(treeNode, res);
        res.forEach(System.out::print);
    }
}
